package com.wowangz.cms.systemmanage.preferential.api;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.Gson;
import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.api.UserContext;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.datadictionary.entity.CfgDataDictValue;
import com.wowangz.cms.systemmanage.datadictionary.service.CfgDataDictService;
import com.wowangz.cms.systemmanage.preferential.entity.TblPreferentialCode;
import com.wowangz.cms.systemmanage.preferential.service.TblPreferentialCodeService;
import com.wowangz.cms.user.pojo.User;
import com.wowangz.cms.user.service.UserService;

@Scope("prototype")
@Controller
public class TblPreferentialCodeController extends BaseController{

	private static Logger logger = LoggerFactory.getLogger(TblPreferentialCodeController.class);
	
	/**
	 * 点击菜单"用户优惠码"显示“用户优惠码”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/preferential/queryPreferentialCodeList.web")
	public String queryPreferentialCodeList(HttpServletRequest request, HttpServletResponse response, Model model) {
		CfgDataDictService cfgDataDictService = (CfgDataDictService) IssTransactionContainer.getInstance(CfgDataDictService.class, false);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("dataDictTypeId", "1");
		List<CfgDataDictValue> mediumList = cfgDataDictService.findCfgDataDictListByType(map);
		map.put("dataDictTypeId", "2");
		List<CfgDataDictValue> channelList = cfgDataDictService.findCfgDataDictListByType(map);
		model.addAttribute("mediumList", mediumList);
		model.addAttribute("channelList", channelList);
		return "/WEB-INF/jsp/systemmanage/preferential/preferentialCodeList";
	}
	
	/**
	 * 打开“用户优惠码”列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/systemmanage/preferential/queryPreferentialCodeListInfoDataGrid.json")
	public void queryPreferentialCodeListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());

			TblPreferentialCodeService preferentialCodeService = (TblPreferentialCodeService) IssTransactionContainer.getInstance(TblPreferentialCodeService.class, false);
			UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
			long resultCount = preferentialCodeService.findPreferentialCodeCount(map);
			List<TblPreferentialCode> resultList = preferentialCodeService.findPreferentialCodeList(map);
			for(TblPreferentialCode result : resultList){
				User user1 = userService.findUserById(result.getCreater());
				User user2 = userService.findUserById(result.getDeadlineEditer());
				if(user1 != null){
					result.setCreater(user1.getUsername());
				}	
				if(user2 != null){
					result.setDeadlineEditer(user2.getUsername());
				}	
			}

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.STRING);
			dataStyle.addDepict("code", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("preferentialType", SysConstant.PreferentialType.class, "getName", new Class[] { String.class });
			//dataStyle.addDepict("preferentialType", DataTypeConstant.STRING);
			dataStyle.addDepict("maxLimit", DataTypeConstant.STRING);
			dataStyle.addDepict("preferentialRatio", DataTypeConstant.LONG);
			dataStyle.addDepict("medium", DataTypeConstant.STRING);
			dataStyle.addDepict("channel", DataTypeConstant.STRING);
			dataStyle.addDepict("dataStatus", DataTypeConstant.STRING);
			dataStyle.addDepict("createTime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("creater", DataTypeConstant.STRING);
			dataStyle.addDepict("usedTime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("userId", DataTypeConstant.STRING);
			dataStyle.addDepict("usedResult", DataTypeConstant.STRING);
			dataStyle.addDepict("deadlineTime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("actualDeadlineTime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("deadlineEditer", DataTypeConstant.STRING);
			
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
			logger.info("加载用户优惠码列表数据成功");
		} catch (Exception e) {
			logger.error("加载用户优惠码列表数据失败",e);
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转用户优惠码添加页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/preferential/toAddPreferentialCode.web")
	public String toAddPreferentialCode(HttpServletRequest request, HttpServletResponse response, Model model) {
		CfgDataDictService cfgDataDictService = (CfgDataDictService) IssTransactionContainer.getInstance(CfgDataDictService.class, false);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("dataDictTypeId", "1");
		List<CfgDataDictValue> mediumList = cfgDataDictService.findCfgDataDictListByType(map);
		map.put("dataDictTypeId", "2");
		List<CfgDataDictValue> channelList = cfgDataDictService.findCfgDataDictListByType(map);
		model.addAttribute("mediumList", mediumList);
		model.addAttribute("channelList", channelList);
		return "/WEB-INF/jsp/systemmanage/preferential/preferentialCodeAdd";
	}
	
	/**
	 * 新增用户优惠码
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/preferential/addPreferentialCode.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void addPreferentialCode(HttpServletRequest request, HttpServletResponse response, Model model) {
		TblPreferentialCodeService preferentialCodeService = (TblPreferentialCodeService) IssTransactionContainer.getInstance(TblPreferentialCodeService.class, true);
		TblPreferentialCode preferentialCode = null;
		String dataJson = "";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			preferentialCode = (TblPreferentialCode) ServletUtils.getParametersToBaseEntity(request, TblPreferentialCode.class);
			preferentialCode.setCreater(String.valueOf(userContext.getLoginUser().getId()));
			List<String> preferentialCodeList = preferentialCodeService.addPreferentialCodeList(preferentialCode);
			resultMap.put("preferentialCodeList", preferentialCodeList);
			resultMap.put("message", MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			resultMap.put("messageType", UserContext.MessageType.INFO);			
			logger.info("新增用户优惠码成功");
		} catch (Exception e) {
			logger.error("新增用户优惠码失败",e);
			e.printStackTrace();
			resultMap.put("message", MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
			resultMap.put("messageType", UserContext.MessageType.ERROR);
		}finally{
			try {
				dataJson = new Gson().toJson(resultMap);
				response.getWriter().write(dataJson);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
/*	
	@RequestMapping(value = "/systemmanage/preferential/validationPreferentialCode.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validationPreferentialCode(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		TblPreferentialCodeService preferentialCodeService = (TblPreferentialCodeService) IssTransactionContainer.getInstance(TblPreferentialCodeService.class, false);
		try {
			TblPreferentialCode preferentialCode = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			preferentialCode = (TblPreferentialCode) ServletUtils.getParametersToBaseEntity(request, TblPreferentialCode.class);
			
			if(null != preferentialCode.getId()){
				map.put("id", preferentialCode.getId());
			}
			map.put("code", preferentialCode.getCode());
			if(!preferentialCodeService.validationPreferentialCode(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.preferential.alert1"));
			}
			
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	*/
	/**
	 * 过期用户优惠码
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/preferential/deletePreferentialCode.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deletePreferentialCode(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		TblPreferentialCodeService preferentialCodeService = (TblPreferentialCodeService) IssTransactionContainer.getInstance(TblPreferentialCodeService.class, true);
		try {
			String id = getRequest().getParameter("id");
			TblPreferentialCode preferentialCode = new TblPreferentialCode();
			preferentialCode.setId(id);
			preferentialCode.setDataStatus("UseUp");
			preferentialCode.setActualDeadlineTime(new Date());
			preferentialCode.setDeadlineEditer(String.valueOf(userContext.getLoginUser().getId()));
			preferentialCodeService.updatePreferentialCode(preferentialCode);
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.preferential.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
			logger.info("过期用户优惠码[{}]成功",preferentialCode.getCode());
		} catch (Exception e) {
			logger.error("过期用户优惠码失败",e);
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.preferential.alert4"));
		}
	}
	
}
